package server.web;

import java.util.LinkedList;
import java.util.Queue;

import server.server.User;

public class WebUser extends User{
    private volatile long _lastHeartbeat;
    private final Queue<String> _msgs;
    private boolean _shutted;

    public WebUser(String name, long uid) {
        super(null);
        setName(name);
        setUID(uid);
        _shutted = false;
        _msgs = new LinkedList<>();
    }

    public void heartbeat() {
        _lastHeartbeat = System.currentTimeMillis();
    }

    public boolean isDead() {
        return (System.currentTimeMillis() - _lastHeartbeat > HttpServer.HEARTBEAT_TIMEOUT) || _shutted;
    }

    // 查看消息队列，无消息返回null
    public String check() {
        if (!_msgs.isEmpty()) {
            synchronized (_msgs) {
                return _msgs.poll();
            }
        } else {
            return null;
        }
    }
    
    @Override
    public void recv(String msg) {
        if (!msg.isEmpty()) {
            synchronized (_msgs) {
                _msgs.offer(msg);
            }
        }
    }

    @Override
    public void shutdown() {
        _shutted = true;
    }
}